package cloud.maque.base.dingding.impl;

import cloud.maque.base.dingding.conf.DingDingClientConfig;
import cloud.maque.base.dingding.hander.DingdingTokenServiceHander;
import cloud.maque.base.dingding.response.DingdingUserReponse;
import cloud.maque.base.dingding.service.DingdingUserService;
import cloud.maque.base.dingding.utils.DomainHelper;
import cloud.maque.framework.conf.PlatformConfigProperties;
import com.alibaba.fastjson.JSON;
import com.aliyun.dingtalkcontact_1_0.models.GetUserHeaders;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserGetbyunionidRequest;
import com.dingtalk.api.response.OapiUserGetbyunionidResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zhuyf
 * @date 2023/3/3 12:18
 */
@Service
public class DingdingUserServiceImpl implements DingdingUserService {

    @Autowired
    DingdingTokenServiceHander tokenServiceHander;

    @Autowired
    DomainHelper helper;

    @Autowired
    PlatformConfigProperties platformConfigProperties;

    @Override
    public DingdingUserReponse GetMyUser(String accessToken) {

        com.aliyun.dingtalkcontact_1_0.Client client = null;
        try {
            client = DingDingClientConfig.contactClient();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        GetUserHeaders getUserHeaders = new GetUserHeaders();
        getUserHeaders.xAcsDingtalkAccessToken = accessToken;
        try {
            String me = JSON.toJSONString(client.getUserWithOptions("me", getUserHeaders, new RuntimeOptions()).getBody());
            DingdingUserReponse userReponse = JSON.parseObject(me, DingdingUserReponse.class);
            return userReponse;
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                throw new RuntimeException(err.message);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                throw new RuntimeException(err.message);
            }

        }

        return null;
    }

    /***
     * 根据unionid获取用户userid
     * https://open.dingtalk.com/document/isvapp/query-a-user-by-the-union-id
     * @param Unionid
     * @return
     */
    @Override
    public String GetUserIdByUnionid(String Unionid) {

        return GetUserIdByUnionid(platformConfigProperties.getDingding().getAppKey(), platformConfigProperties.getDingding().getAppSecret(), Unionid);
    }

    @Override
    public String GetUserIdByUnionid(String appKey, String appSecret, String Unionid) {
        String accessToken = tokenServiceHander.GetAccessEnterpriseToken(appKey, appSecret);

        DingTalkClient client = new DefaultDingTalkClient(helper.GetUrl("/user/getbyunionid"));
        OapiUserGetbyunionidRequest req = new OapiUserGetbyunionidRequest();
        req.setUnionid(Unionid);
        try {
            OapiUserGetbyunionidResponse rsp = client.execute(req, accessToken);
            if (rsp.getErrmsg().equals("ok")) {
                return rsp.getResult().getUserid();
            } else {
                throw new RuntimeException(rsp.getErrmsg());
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}
